package contest.util;

import contest.enums.EUploadFileResult;
import java.io.File;

public class UploadFile {

    String pathLocation;
    String[] fileType;
    String renameFile;
    File fileUpload;
    int maxSize;
    boolean isCreateFolderNotFound;

    public UploadFile(String pathLocation, String renameFile, File fileUpload, int maxSize, String[] fileType) {
        this.pathLocation = pathLocation;
        this.fileType = fileType;
        this.fileUpload = fileUpload;
        this.renameFile = renameFile;
        this.isCreateFolderNotFound = true;
        this.maxSize = maxSize;
    }

    public EUploadFileResult upload() {
        if (this.fileUpload != null) {
            File uploadDir = new File(this.pathLocation);
            if (this.isCreateFolderNotFound && !uploadDir.exists()) {
                uploadDir.mkdir();
            }

            if (!this.checkFileType()) {
                fileUpload.delete();
                return EUploadFileResult.UPLOADFILE_INCORRECT_FILETYPE;
            } else if (!checkFileSize()) {
                fileUpload.delete();
                return EUploadFileResult.UPLOADFILE_OVER_MAXSIZE;
            } else {
                File file1 = new File(this.pathLocation + this.renameFile + this.getExtension());
                if (file1 != null) {
                    file1.delete();
                }
                this.fileUpload.renameTo(file1);
                return EUploadFileResult.UPLOADFILE_SUCCESS;
            }
        } else {
            fileUpload.delete();
            return EUploadFileResult.UPLOADFILE_NOT_FOUND;
        }
    }

    public boolean checkFileType() {
        String filename = this.fileUpload.getName();
        int index = filename.lastIndexOf(".");
        String extension = filename.substring(index);
        for (int i = 0; this.fileType != null && i < this.fileType.length; i++) {
            if (this.fileType[i].equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    public String getExtension() {
        String filename = this.fileUpload.getName();
        int index = filename.lastIndexOf(".");
        String extension = filename.substring(index);
        return extension;
    }

    public boolean checkFileSize() {
        long size = this.fileUpload.length();
        if (this.maxSize >= size) {
            return true;
        }
        return false;
    }

    public void setCreateFolderNotFound(boolean isCreateFolderNotFound) {
        this.isCreateFolderNotFound = isCreateFolderNotFound;
    }
}
